package com.onlineMIS.ORM.DAO.headQ.barCodeGentor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.BelongToVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.BrandVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Product;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Year;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.StrCheckUtils;

@Repository
public class BrandDaoImpl extends BaseDAO<Brand> {
	@Override
	public void saveOrUpdate(Brand brand, boolean cached) {
		if (cached)
			getHibernateTemplate().setCacheQueries(true);

		if (brand.getChainStore() != null  && brand.getChainStore().getChain_id() == 0 )
			brand.setChainStore(null);
		
	
		     getHibernateTemplate().saveOrUpdate(brand);
		

	}

	/*
	 * 根据品牌归属 - 获取所有归属信息 - 下拉框使用
	 * range 1 : 包括所有
	 *       2 : 只包括所有和千禧和禧乐仓
	 *       3 : 只包括千禧和禧乐仓
	 */
	public List<BelongToVO> getBelongTos(int range) {
		List<BelongToVO> belongToVOs = new ArrayList<BelongToVO>();
		
		if (range == 1 || range == 2) {
		   BelongToVO vo = new BelongToVO();
		   vo.setId(Common_util.ALL_RECORD);
		   vo.setBelongToName("所有归属");
		   belongToVOs.add(vo);
		}
		if (Brand.belongToMap.size() != 0) {
			Iterator<Map.Entry<Integer, String>> iterator = Brand.belongToMap.entrySet().iterator();
			while(iterator.hasNext()) {
				 Map.Entry<Integer, String> entry = iterator.next();
				BelongToVO toVO = new BelongToVO();
				toVO.setId(entry.getKey());
				
				if ((range ==2 || range ==3) ) {
					if ((toVO.getId() == Brand.BELONG_TO_QX || toVO.getId() == Brand.BELONG_TO_XLC)) {
						toVO.setBelongToName(entry.getValue());
						belongToVOs.add(toVO);
					}
					
				} else{
					toVO.setBelongToName(entry.getValue());
					belongToVOs.add(toVO);
				}

			}
		}		
		return belongToVOs;
	}
	
	
	/**
	 * 获取总部所有品牌
	 * @return
	 */
	public List<BrandVO> selectBrands() {
		List<BrandVO> brandVOs = new ArrayList<BrandVO>();
		DetachedCriteria criteria = DetachedCriteria.forClass(Brand.class);
//		if (StrCheckUtils.isNumber(q)) {
//			criteria.add(Restrictions.like("pinyin", q, MatchMode.ANYWHERE));	
//		}else {
//			criteria.add(Restrictions.like("brand_Name", q, MatchMode.ANYWHERE));
//		}
		criteria.add(Restrictions.isNull("chainStore.chain_id"));			
		List<Brand> brands = this.getByCritera(criteria, true);
		for (Brand brand : brands) {
			BrandVO bVo = new BrandVO(brand);
			brandVOs.add(bVo);
		}
		return brandVOs;
	}

}
